const Base = require('./base.js');

module.exports = class extends Base {
  /**
   * 发布文章
   */
  async writePostAction() {
    const content = {
      password: this.post('password'),
      allowComment: this.post('allowComment'),
      allowPing: this.post('allowPing'),
      allowFeed: this.post('allowFeed'),
      slug: this.post('slug'),
      tags: this.post('tags'),
      text: this.post('text'),
      visibility: this.post('visibility')
    };
    content.authorId = this.ctx.state.uid;
    content.category = this.post('category');
    content.title = this.post('title') || '未命名文档';
    content.created = Number.parseInt(Date.now() / 1000);
    if (this.post('markdown')) {
      content.text = '<!--markdown-->' + content.text;
    }

    // 发布还是保存
    content.type = 'post';
    if (think.isEmpty(content.visibility)) {
      content.status = 'publish';
    } else if (content.visibility === 'password' || !['private', 'waiting', 'publish', 'hidden'].includes(content.visibility)) {
      if (think.isEmpty(content.password) || content.visibility !== 'password') {
        content.password = '';
      }
      content.status = 'publish';
    } else {
      content.status = content.visibility;
      content.password = '';
    }

    const realId = await think.model('contents').insertContent(content);
    if (realId > 0) {
      console.log('添加文章成功' + realId);
    } else {
      console.log('添加文章失败');
    }
    return this.redirect('/admin/manage/posts');
  }
};
